
import struct
import ctypes
from scapy.compat import bytes_encode, orb

def hexdump2(x,start,end):
    """
    返回十六进制下数据包从start到end位置的十六进制字符串，从scapy源码utils.py工具集hexdump改进而来
    请注意start和end只能是偶数（如果不是偶数会自动前移一位）
    Build a tcpdump like hexadecimal view（from start to end）

    :param x: a Packet
    :returns: a String
    """
    s = ""
    x = bytes_encode(x)
    i = int(start/2)#1byte数据为8位二进制数，1个十六进制数为4位二进制数
    x_len=int(end/2)
    while start <= end:
        for j in range(16):
            if i + j < x_len:
                s += "%02X" % orb(x[i + j])#ord为从给定字符值中获取数字值，"%02X"为转为16进制，不足补0.
        i += 16
        start+=1
    return s

def float_to_hex(f):
    return hex(struct.unpack('<I', struct.pack('<f', f))[0])
def float2hex(s):
    fp = ctypes.pointer(ctypes.c_float(s))
    cp = ctypes.cast(fp,ctypes.POINTER(ctypes.c_long))
    return hex(cp.contents.value)

def hex_to_float(h):
    i = int(h,16)
    return struct.unpack('<f',struct.pack('<I', i))[0]
def hex2float(h):
    i = int(h,16)
    cp = ctypes.pointer(ctypes.c_int(i))
    fp = ctypes.cast(cp,ctypes.POINTER(ctypes.c_float))
    return fp.contents.value


if __name__ == '__main__':
    pass

